package com.heer.gymnasium.module.article.views;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseRefreshActivity;
import com.heer.gymnasium.module.article.beans.ArticleDetailBean;
import com.heer.gymnasium.module.article.beans.EvaluateBean;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.views.FindFragment;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.util.DialogUtils;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.StringUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.view.MyListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by zy on 2018/1/24.
 * 文章详情页
 */

public class ArticleActivity extends BaseRefreshActivity {

    private final static int RES_ID_ROOT = R.layout.layout_advisory_detail;
    private final static int LAYOUT_NAME_ID = R.id.layout_advisory_detail_titlename_tv;
    private final static int LAYOUT_TIME_ID = R.id.layout_advisory_detail_time_tv;
    private final static int LAYOUT_CONTENT_ID = R.id.layout_advisory_detail_webview;
    private final static int LAYOUT_LIST_ID = R.id.layout_advisory_detail_lv;
    private final static int LAYOUT_REFRESH_ID = R.id.layout_advisory_detail_refresh_srl;
    private final static int LAYOUT_EVALUATION_ID = R.id.layout_advisory_detail_evaluation_tv;
    private final static int LAYOUT_JOIN_ID = R.id.layout_advisory_detail_join_tv;
    private final static int LAYOUT_ACTIVE_ONLY_PANEL = R.id.layout_advisory_detail_active_only_ll;
    private final static int LAYOUT_END_TIME = R.id.layout_advisory_detail_end_time_tv;
    private final static int LAYOUT_LIMIT_NUM = R.id.layout_advisory_detail_limit_num_tv;
    private final static int LAYOUT_LOAD_MORE = R.id.layout_advisory_detail_more_tv;

    private final static int ITEM_LAYOUT = R.layout.item_evaluation;
    private final static int ITEM_HEAD_ID = R.id.item_evaluation_head_iv;
    private final static int ITEM_NAME_ID = R.id.item_evaluation_username_tv;
    private final static int ITEM_TIME_ID = R.id.item_evaluation_time_tv;
    private final static int ITEM_CONTENT_ID = R.id.item_evaluation_content_tv;
    private final static int ITEM_AUTHOR_ID = R.id.item_evaluation_author_ll;
    private final static int ITEM_REPLY_ID = R.id.item_evaluation_replycontent_tv;


    @BindView(LAYOUT_NAME_ID)
    TextView titleTextView;
    @BindView(LAYOUT_TIME_ID)
    TextView timeTextView;
    @BindView(LAYOUT_CONTENT_ID)
    WebView webView;
    @BindView(LAYOUT_LIST_ID)
    MyListView listView;
    @BindView(LAYOUT_ACTIVE_ONLY_PANEL)
    View activeOnlyPanel;
    @BindView(LAYOUT_END_TIME)
    TextView tvEndTime;
    @BindView(LAYOUT_LIMIT_NUM)
    TextView tvLimitNum;
    @BindView(LAYOUT_LOAD_MORE)
    TextView tvMore;
    @BindView(LAYOUT_JOIN_ID)
    View vJoin;

    private List<EvaluateBean.Item> data;
    private QuickTypeAdapter<EvaluateBean.Item> adapter;
    private ArticleActivity $this;
    private boolean isFirst = true;

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_ROOT);
        setRefreshResId(LAYOUT_REFRESH_ID);
    }

    @Override
    protected void initView() {
        super.initView();
        webView.onResume(); titleUtils.startMainActivity($this);
        data = new ArrayList<>();
        adapter = new QuickTypeAdapter<EvaluateBean.Item>(this, data, ITEM_LAYOUT) {
            @Override
            public void bindData4View(ViewHolder holder, EvaluateBean.Item data, int type, int pos) {
                if (!TextUtils.isEmpty(data.getReply())) {
                    holder.setVisibility(ITEM_AUTHOR_ID, View.VISIBLE);
                    holder.setText(ITEM_REPLY_ID, Html.fromHtml(data.getReply()));
                } else {
                    holder.setVisibility(ITEM_AUTHOR_ID, View.GONE);
                }
                holder.setText(ITEM_CONTENT_ID, data.getContent());
                holder.setText(ITEM_TIME_ID, data.getCreate_time());
                holder.setText(ITEM_NAME_ID, data.getShowname());
                ImageUtil.loadUrl(context, data.getAvatar(), R.drawable.ic_face_bg, (ImageView) holder.getView(ITEM_HEAD_ID));
            }
        };
        listView.setAdapter(adapter);
        getArticle();

    }


    @Override
    protected void loadData(boolean loadMore) {
        super.loadData(loadMore);
        if (pageNo == 1) {
            layoutRefresh.setDirection(SwipyRefreshLayoutDirection.BOTTOM);
        }
        getReplyList();
        setRefresh(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirst) {
            pageNo = 1;
            layoutRefresh.setDirection(SwipyRefreshLayoutDirection.BOTTOM);
            getReplyList();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
    }

    public static void startActivity(Context context, String id, int type) {
        Intent mIntent = new Intent(context, ArticleActivity.class);
        mIntent.putExtra(EXTRA_ID, id);
        mIntent.putExtra(EXTRA_TYPE, type);
        context.startActivity(mIntent);
    }

    private void setRefresh(boolean flag) {
        if (layoutRefresh != null) {
            layoutRefresh.setRefreshing(flag);
        }
    }

    //获得文章信息
    private void getArticle() {
        String id = getIntent().getStringExtra(EXTRA_ID);
        int type = getIntent().getIntExtra(EXTRA_TYPE, FindFragment.ARTICLE_TYPE_NEWS);
        if (type == FindFragment.ARTICLE_TYPE_NEWS) {
            titleUtils.setTitleText("文章详情");
            activeOnlyPanel.setVisibility(View.GONE);
        } else {
            titleUtils.setTitleText("活动详情");
            activeOnlyPanel.setVisibility(View.VISIBLE);
        }
        mAppHelper.apiService().getArticle(id).enqueue(new BaseCallback<ApiResponse<ArticleDetailBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<ArticleDetailBean>> call, Response<ApiResponse<ArticleDetailBean>> response) {
                ArticleDetailBean bean = response.body().getData();
                titleTextView.setText(bean.getTitle());
                tvEndTime.setText(StringUtils.timeStamp10ToDate(bean.getEnd_time(), StringUtils.DATE_FORMAT_CN));
                if (TextUtils.equals("0", bean.getMax_num())) {
                    tvLimitNum.setText("不限");
                } else {
                    tvLimitNum.setText(String.format("%s人", bean.getMax_num()));
                }

                if (System.currentTimeMillis() > StringUtils.toInt(bean.getEnd_time()) * 1000L) {
                    vJoin.setVisibility(View.GONE);
                } else {
                    vJoin.setVisibility(View.VISIBLE);
                }

                timeTextView.setText(StringUtils.timeStamp10ToDate(bean.getTime(), StringUtils.DATE_FORMAT));
                String css = "<style>body{padding:0 10px 0 10px;}</style>";
                webView.loadDataWithBaseURL(null, css + bean.getContent(), "text/html", "utf-8", null);
                webView.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        int w = View.MeasureSpec.makeMeasureSpec(0,
                                View.MeasureSpec.UNSPECIFIED);
                        int h = View.MeasureSpec.makeMeasureSpec(0,
                                View.MeasureSpec.UNSPECIFIED);
                        view.measure(w, h);
                        super.onPageFinished(view, url);

                    }
                });
            }

        });
    }

    //获得文章评价列表
    private void getReplyList() {
        isFirst = false;
        String id = getIntent().getStringExtra(EXTRA_ID);
        mAppHelper.apiService().getReplyList(id, pageNo + "").enqueue(new BaseCallback<ApiResponse<EvaluateBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<EvaluateBean>> call, Response<ApiResponse<EvaluateBean>> response) {
                if (pageNo == 1) {
                    data.clear();
                }
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (total <= current * per_page) {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.TOP);
                    tvMore.setVisibility(View.GONE);
                } else {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.BOTH);
                    tvMore.setVisibility(View.VISIBLE);
                }

                data.addAll(response.body().getData().getData());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    @OnClick(LAYOUT_EVALUATION_ID)
    public void addArticleReply() {
        String id = getIntent().getStringExtra(EXTRA_ID);
        AddArticleReplyActivity.startActivity(this, id);
    }

    @OnClick(LAYOUT_JOIN_ID)
    public void doJoin() {
        String id = getIntent().getStringExtra(EXTRA_ID);
        mAppHelper.apiService().doEnroll(id).enqueue(new BaseCallback<ApiResponse<String>>() {
            @Override
            public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                DialogUtils.showDialog($this, "", response.message(), "", "", DialogUtils.DIALOG_TYPE_SINGLE, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtils.dismissDialog();
                    }
                });
            }
        });
    }
}
